<?php

class RForm {

    private $formId = "";
    private $calculateJSFunction = "";
    private $calculateService = "";
    private $fields = array();
    private $fieldIds = array();
    private $fieldNames = array();

    public function __construct($formId, $calculateService = "") {
        $this->formId = $formId;
        $this->calculateJSFunction = "RFormCalc_" . md5($formId);
        $this->calculateService = $calculateService;
    }

    private function getJqueryFieldIds() {
        $tmp = Array();
        if (is_array($this->fieldIds)) {
            foreach ($this->fieldIds as $id) {
                $tmp[] = "#" . $id;
            }
        }
        return implode(",", $tmp);
    }

    private function getFieldId($name) {
        $id = md5("rform_" . $this->formId . "_" . $name);
        if (!in_array($id, $this->fieldIds)){
            $this->fieldIds[] = $id;
        }
        if (!in_array($name, $this->fieldNames)){
            $this->fieldNames[] = $name;
        }
        return $id;
    }

    public function addTextField($name) {
        $id = $this->getFieldId($name);
        $this->fields[$id] = "<input placeholder='Skriv dit navn ..' 
            class='form-control' 
            onkeyup='javascript:if(event.keyCode == 13){this.blur();}'
            onclick='javascript:this.focus(); this.select();' 
            style='height:22px; padding:2px;' 
            id='" . $id . "' 
            name='" . $name . "' 
            onchange='javascript:" . $this->calculateJSFunction . "();' />";
    }

    public function drawField($name) {
        $id = $this->getFieldId($name);
        if (isset($this->fields[$id])) {
            echo $this->fields[$id];
        } else {
            echo "<span style='color:red;'>Error: Field not found!</span>";
        }
    }

    public function init() {
        echo "<script>";
        echo "function " . $this->calculateJSFunction . "_getID(name){";
        foreach ($this->fieldNames as $f){
            echo "if (name==\"".$f."\"){";
            echo "return \"".$this->getFieldId($f)."\";";
            echo "}";
        }
        echo "}";
        
        
        echo "function " . $this->calculateJSFunction . "(){";
        if (trim($this->calculateService) != "") {
            echo "$.ajax({"
            . "type:\"POST\","
            . "dataType:\"json\","
            . "url:\"" . $this->calculateService . "\","
            . "data:$('" . $this->getJqueryFieldIds() . "').serialize(),"
            . "success:function(data){";
            echo "$.each( data, function( key, val ) {"
            . "var tmpId = " . $this->calculateJSFunction . "_getID(key);"
            . "$(\"#\"+tmpId).val(val);"
            . "});";
            echo "}});";
        }
        echo "}";
        echo "</script>";
    }

}
